﻿using BW.MesProject.BasicData.Domain.基础;
using BW.MesProject.BasicData.Infrastructure;
using BW.MesProject.Public.ErrorCode;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OfficeOpenXml;
using System.Drawing;

namespace BW.MesProject.BasicData.Host.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ProductItemController : ControllerBase
    {
        private readonly IProductItemServices productItemServices;

        public ProductItemController(IProductItemServices productItemServices)
        {
            this.productItemServices = productItemServices;
        }
        /// <summary>
        /// 添加或更新产品物料信息
        /// </summary>
        /// <param name="model">产品物料模型</param>
        /// <returns>操作结果</returns>
        [HttpPost]
        public ApiResult<int> AddProductItem(ProductItemModel model)
        {
            return productItemServices.AddProductItem(model);
        }

        /// <summary>
        /// 删除产品物料（逻辑删除）
        /// </summary>
        /// <param name="id">产品物料ID</param>
        /// <returns>操作结果</returns>
        [HttpPut]
        public ApiResult<int> DeleteProductItem(long id)
        {
           return productItemServices.DeleteProductItem(id);
        }

        /// <summary>
        /// 获取所有产品物料
        /// </summary>
        /// <returns>产品物料列表</returns>
        [HttpGet]
        public ApiResult<List<ProductItemModel>> GetAllProductItem()
        {
               return productItemServices.GetAllProductItem();
        }

        /// <summary>
        /// 分页查询产品物料
        /// </summary>
        /// <param name="Productitemcode">产品物料编码</param>
        /// <param name="Productitemname">产品物料名称</param>
        /// <param name="Producttype">产品类型</param>
        /// <param name="pageindex">页码</param>
        /// <param name="pagesize">每页大小</param>
        /// <returns>分页结果</returns>
        [HttpGet]
        public ApiPaging<ProductItemModel> GetProductItem(string? Productitemcode, string? Productitemname, string? Producttype, int pageindex, int pagesize)
        {
          return productItemServices.GetProductItem(Productitemcode, Productitemname, Producttype, pageindex, pagesize);
        }

        /// <summary>
        /// 根据ID获取产品物料
        /// </summary>
        /// <param name="id">产品物料ID</param>
        /// <returns>产品物料信息</returns>
        [HttpGet]
        public ApiResult<ProductItemModel> GetProductItemById(long id)
        {
            return productItemServices.GetProductItemById(id);
        }
        //导出产品物料
        /// <summary>
        /// 导出产品物料到Excel
        /// </summary>
        /// <returns>Excel文件</returns>
        [HttpGet]
        public IActionResult ExportProductItemToExcel()
        {
            try
            {
                // 获取所有产品物料数据
                var result = productItemServices.GetAllProductItem();
                if (result.Code != ApiEnums.Success || result.Data == null)
                {
                    return BadRequest("获取产品物料数据失败");
                }
                
                // 使用所有数据
                var data = result.Data;
                
                // 创建Excel包
                using (var package = new ExcelPackage())
                {
                    // 添加工作表
                    var worksheet = package.Workbook.Worksheets.Add("产品物料信息");
                    
                    // 设置表头样式
                    var headerRange = worksheet.Cells[1, 1, 1, 10];
                    headerRange.Style.Font.Bold = true;
                    headerRange.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                    headerRange.Style.Fill.BackgroundColor.SetColor(Color.LightGray);
                    headerRange.Style.Font.Color.SetColor(Color.Black);
                    headerRange.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                    
                    // 添加表头
                    string[] headers = new string[] 
                    {
                        "产品物料编码", "产品物料名称", "规格型号", "单位", 
                        "预警值", "工艺路线", "物料群组编号", "群组类型", "描述", "创建时间"
                    };
                    
                    for (int i = 0; i < headers.Length; i++)
                    {
                        worksheet.Cells[1, i + 1].Value = headers[i];
                    }
                    
                    // 填充数据
                    if (data.Any())
                    {
                        int row = 2;
                        foreach (var item in data)
                        {
                            worksheet.Cells[row, 1].Value = item.Productitemcode;
                            worksheet.Cells[row, 2].Value = item.Productitemname;
                            worksheet.Cells[row, 3].Value = item.Productitemspecification;
                            worksheet.Cells[row, 4].Value = item.Productitemunit;
                            worksheet.Cells[row, 5].Value = item.Productitemwarningvalue;
                            worksheet.Cells[row, 6].Value = item.Processrouteid;
                            worksheet.Cells[row, 7].Value = item.Materialgroupid;
                            worksheet.Cells[row, 8].Value = item.Producttype;
                            worksheet.Cells[row, 9].Value = item.Productitemdescribe;
                            worksheet.Cells[row, 10].Value = item.CreatedTime;
                            
                            // 设置日期格式
                            if (item.CreatedTime != default)
                            {
                                worksheet.Cells[row, 10].Style.Numberformat.Format = "yyyy-MM-dd HH:mm:ss";
                            }
                            
                            row++;
                        }
                        
                        // 设置数据区域的样式
                        var dataRange = worksheet.Cells[2, 1, row - 1, 10];
                        dataRange.Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Left;
                        dataRange.Style.Border.Top.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                        dataRange.Style.Border.Bottom.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                        dataRange.Style.Border.Left.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                        dataRange.Style.Border.Right.Style = OfficeOpenXml.Style.ExcelBorderStyle.Thin;
                    }
                    
                    // 自动调整列宽
                    worksheet.Cells.AutoFitColumns();
                    
                    // 将Excel包转换为字节数组
                    var excelData = package.GetAsByteArray();
                    
                    // 返回Excel文件
                    return File(
                        excelData,
                        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                        $"产品物料信息_{DateTime.Now:yyyyMMddHHmmss}.xlsx"
                    );
                }
            }
            catch (Exception ex)
            {
                return BadRequest($"导出Excel失败: {ex.Message}");
            }
        }
    }
}
